package com.example.springsecurity.utill;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {

    public static SecretKey generalKey(){
        String codeKey="pL52kjtHZCcKZZ8ukV4nBA==";
       byte[] encodedKey = Base64.getDecoder().decode(codeKey);
       SecretKey key = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
       return key;
    }

    public static String createJwt(String subject){

        //定义生成签名的算法
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
        //定义生成签名的密钥
        SecretKey key=generalKey();

        //借助第三方依赖组件
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //用户id
                //.setId(id)
                //主题
                .setSubject(subject)
                //签发时间，默认是生成时间
                .setIssuedAt(new Date())
                //加密和密钥
                .signWith(algorithm,key);

        //设定过期时间7天
        builder.setExpiration(new Date(System.currentTimeMillis()+ 600L*1000*6*24*7));


        //生成token
        return builder.compact();


    }


    // 解析jwt
    public static Claims parseToken(String jwt) throws Exception {
        SecretKey key = generalKey(); // 签名秘钥，和生成的签名的秘钥一模一样
        Claims claims = Jwts.parser() // 得到DefaultJwtParser
                .setSigningKey(key) // 设置签名的秘钥
                .parseClaimsJws(jwt).getBody(); // 设置需要解析的jwt
        return claims;
    }



    // jwt是否过期(过期返回ture
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

}
